package com.example.chenkezhen

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.TextView
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class chenkezhen2022180704 : AppCompatActivity() {

    private lateinit var Min: EditText
    private lateinit var Max: EditText
    private lateinit var tvPrimes: TextView
    private lateinit var btnStart: Button
    private lateinit var btnStop: Button
    private var isCalculating = false
    private val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Min = findViewById(R.id.minNumber)
        Max = findViewById(R.id.maxNumber)
        tvPrimes = findViewById(R.id.resultTextView)
        btnStart = findViewById(R.id.calculateButton)
        btnStop = findViewById(R.id.StopButton)

        btnStart.setOnClickListener {
            isCalculating = true
            Thread {
                val min = Min.text.toString().toInt()
                val max = Max.text.toString().toInt()
                val primes = StringBuilder()
                for (i in min..max) {
                    if (isCalculating && isPrime(i)) {
                        val prime = "$i\n"
                        handler.post {
                            primes.append(prime)
                            tvPrimes.text = primes.toString()
                        }
                    }
                }
                savePrimes(primes.toString())
            }.start()
        }

        btnStop.setOnClickListener {
            isCalculating = false
        }
    }

    private fun isPrime(number: Int): Boolean {
        if (number <= 1) return false
        for (i in 2..Math.sqrt(number.toDouble()).toInt()) {
            if (number % i == 0) return false
        }
        return true
    }

    private fun savePrimes(primes: String) {
        val fileName = "primes.txt"
        val file = File(filesDir, fileName)
        try {
            FileOutputStream(file).use { fos ->
                fos.write(primes.toByteArray())
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.history -> {
                val intent = Intent(this, HistoryActivity::class.java)
                startActivity(intent)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}
